<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24/024
 * Time: 20:37
 */

namespace app\admin\model;

use think\Db;
use think\facade\Session;

class ChapterDetail extends \think\Model
{
    protected $table = 'sy_tk_chapter_detail';
    /**
     * 获取单条
     * @param $id
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public function _findOne($id){
        $data = $this->where([['id', '=', $id]])->find();
        
        return $data;
    }

    
    /**
    * 通过名称获取信息
    */
    public function _findByName($name){
        return $this->where([['title', '=', $name]])->find();
    }
    

    /**
    * 校验是否被冻结
    */
    public function _checkStatus($id){
        $data = $this->where(array('id'=>$id, 'status'=>1))->find();
        if(empty($data)){
            $this->error = '已禁用';
            return false;
        }
        return true;
    }

    /**
     * 列表
     * @param array $condition
     * @param int $page_size
     * @param string $order_by
     * @return \think\Paginator
     */
    public function _list($condition = [], $page_size = PAGE_SIZE_ADMIN, $order_by = 'sort asc'){
        $obj = $this->alias('u')
            ->field('u.*, cc.chapter_title')
            ->join('sy_tk_chapters cc', 'cc.id = u.chapter_cate', 'LEFT')
            ->order('u.id desc');
        $result = get_page($obj, $condition, $page_size);
       
        return $result;
    }
    
    /**
    * 通过班级id获取plan
    */
    public function _getPlan($class_id){
        return $this->where([['class_id',  '=', $class_id], ['status', '=', 1]])->select();
    }

    /**
     * 添加
     * @param $post
     * @return bool
     */
    public function _create($post){
        $title = trim($post['detail_title']);
        $class_id = (int)$post['chapter_cate'];
        $admin = $this->where([['detail_title', '=', $title],['chapter_cate', '=', $class_id]])->find();
        if($admin){
            $this->error = '数据已存在';
            return false;
        }
        
        $data = $post;
        $time = time();
        $cate_info = Chapter::get($class_id);
        $data['cate']      = $cate_info['cate'];
        $data['create_at'] = $time;
        if(!$this->insert($data)){
            $this->error = '操作失败';
            return false;
        }
        return true;
    }


    /**
     * 删除
     * @param $id
     * @return bool
     */
    public function _remove($id){
        $result = $this->_findOne($id);
        if(!$result){
            $this->error = '无此数据';
            return false;
        }

        if(!$result->delete()){
            $this->error = '操作失败';
            return false;
        }
        return true;
    }
    
    
    /**
     * 批量删除
     * @param $id
     * @return bool
     */
    public function _removeAll($id){
        $ret = $this->where([['id', 'in', $id]])->delete();
        if(!$ret){
            $this->error = '操作失败';
            return false;
        }
        return true;
    }


    /**
     * 详情
     * @param $id
     * @return array|bool
     */
    public function _detail($id){
        $result = $this->_findOne($id)->toArray();
        if(!$result){
            $this->error = '无此数据';
            return false;
        }
        return $result;
    }


    /**
     * 修改
     * @param $post
     * @return bool
     */
    public function _modify($post){
        $result = $this->_findOne($post['id']);
        if(empty($result)){
            $this->error = '数据不存在';
            return false;
        }
        foreach($post as $k=>$v){
            $result->$k = $v;
        }
        if($result->save() === false){
            $this->error = '操作失败';
            return false;
        }
        
        return true;
    }

    /**
    * 设置状态
    */
    public function _setStatus($request){
        $ff = $request['ff'];
        $id = $request['id'];
        if($ff == 1){
            $success = "停用成功";
            $error = "停用失败";
        }elseif($ff == -1){
            $success = "启用成功";
            $error = "启用失败";
        }
        
        
        $where = array('id'=>$id,'status'=>$ff);

        $data = $this->where($where)->find();
        if(empty($data)){
            $this->error = '该数据状态已改变';
            
            return false;
        }
        $data->status = -$ff;
        $ret = $data->save();
        if(!$ret){
            $this->error = $error;
            return false;
        }
        
        return true;
    }
    

    /**
    * 数据总条数
    */
    public function _count($where = []){
        return $this->alias('u')->where($where)->count();
    }

    /**
    * 获取条件
    */
    public function _where($request){
        $p = isset($request['page']) ? $request['page'] : 1;
        $start = isset($request['start']) ? $request['start'] : '';
        $end = isset($request['end']) ? $request['end'] : '';
        $class_id = isset($request['chapter_cate']) ? $request['chapter_cate'] : '';
        $title = isset($request['chapter_title']) ? $request['chapter_title'] : '';
        $chapter_type = isset($request['chapter_type']) ? $request['chapter_type'] : 1;
        
        $request['page'] = $p;
        $request['start'] = $start;
        $request['end'] = $end;
        $request['chapter_title'] = $title;
        $request['chapter_cate'] = $class_id;
        $request['chapter_type'] = $chapter_type;
        
        $search = $request;

        $title = htmlspecialchars(addslashes(str_replace(' ', '', $request['chapter_title'])));
        $request['chapter_title'] = str_replace('%', "\%", $title);
        
        $request['start'] = empty($request['start']) ? '' : strtotime($request['start']);
        $request['end'] = empty($request['end']) ? '' : strtotime($request['end']);
        $tmp = $request;
        foreach($tmp as $k=>$v){
            if(empty($v)){
                unset($tmp[$k]);
            }
        }
        
        $where = '';
        foreach($tmp as $k=>$v){
            if($k == 'start'){
                $start = strtotime($v);
                $where .= "u.created >= $start and ";
            }elseif($k == 'end'){
                $end = strtotime($v) + 24*3600;
                $where .= "u.created <= $end and ";
            }elseif($k == 'title'){
                $where .= "u.chapter_title like '%$v%' and ";
            }elseif($k == 'chapter_cate'){
                $where .= "u.chapter_cate = $v and ";
            }elseif($k == 'chapter_type'){
                $where .= "u.chapter_type = $v and ";
            }
        }
        if(!empty($where)){
            $where = substr($where, 0, -4);
        }
        return array('search'=>$search,'where'=>$where);
    }


    /**
     * 修改
     * @param $post
     * @return bool
     */
    public function _modify_one($post){
        $result = $this->_findOne($post['id']);
        if(empty($result)){
            $this->error = '数据不存在';
            return false;
        }
        foreach($post as $k=>$v){
            $result->$k = $v;
        }
        if($result->save() === false){
            $this->error = '操作失败';
            return false;
        }

        return true;
    }

    /**
     * 添加
     * @param $post
     * @return bool
     */
    public function _create_one($post){
        $title = trim($post['detail_title']);
        $class_id = (int)$post['cate'];
        $admin = $this->where([['detail_title', '=', $title],['cate', '=', $class_id]])->find();
        if($admin){
            $this->error = '数据已存在';
            return false;
        }
        $data = $post;
        $time = time();
        $data['create_at'] = $time;
        if(!$this->insert($data)){
            $this->error = '操作失败';
            return false;
        }
        return true;
    }

    /**
     * 列表
     * @param array $condition
     * @param int $page_size
     * @param string $order_by
     * @return \think\Paginator
     */
    public function _list_one($condition = [], $page_size = PAGE_SIZE_ADMIN, $order_by = 'sort asc'){
        $obj = $this->alias('u')
            ->field('u.*, cc.cate_title')
            ->join('sy_tk_cates cc', 'cc.id = u.cate', 'LEFT')
            ->where('u.chapter_type','gt',1)
            ->order('u.id desc');
        $result = get_page($obj, $condition, $page_size);
        $result0 = $result['list']->all();
        foreach ($result0 as $k=>$v){
            $map0['detail_id'] = $v['id'];
            $map0['q_type']    = 1;
            $q_number_one = Single::where($map0)->count();
            $map1['detail_id'] = $v['id'];
            $map1['q_type']    = 2;
            $q_number_two = Single::where($map1)->count();
            $map2['detail_id'] = $v['id'];
            $map2['q_type']    = 3;
            $q_number_three = Single::where($map2)->count();
            $v['q_number_one']      = $q_number_one;
            $v['q_number_two']      = $q_number_two;
            $v['q_number_three']    = $q_number_three;
            $result['list'][$k] = $v;
        }
        return $result;
    }

    /**
     * 获取条件
     */
    public function _where_one($request){
        $p = isset($request['page']) ? $request['page'] : 1;
        $start = isset($request['start']) ? $request['start'] : '';
        $end = isset($request['end']) ? $request['end'] : '';
        $class_id = isset($request['chapter_cate']) ? $request['chapter_cate'] : '';
        $title = isset($request['chapter_title']) ? $request['chapter_title'] : '';
        $request['page'] = $p;
        $request['start'] = $start;
        $request['end'] = $end;
        $request['chapter_title'] = $title;
        $request['chapter_cate'] = $class_id;
        $search = $request;
        $title = htmlspecialchars(addslashes(str_replace(' ', '', $request['chapter_title'])));
        $request['chapter_title'] = str_replace('%', "\%", $title);

        $request['start'] = empty($request['start']) ? '' : strtotime($request['start']);
        $request['end'] = empty($request['end']) ? '' : strtotime($request['end']);
        $tmp = $request;
        foreach($tmp as $k=>$v){
            if(empty($v)){
                unset($tmp[$k]);
            }
        }

        $where = '';
        foreach($tmp as $k=>$v){
            if($k == 'start'){
                $start = strtotime($v);
                $where .= "u.created >= $start and ";
            }elseif($k == 'end'){
                $end = strtotime($v) + 24*3600;
                $where .= "u.created <= $end and ";
            }elseif($k == 'title'){
                $where .= "u.chapter_title like '%$v%' and ";
            }elseif($k == 'chapter_cate'){
                $where .= "u.chapter_cate = $v and ";
            }
        }
        if(!empty($where)){
            $where = substr($where, 0, -4);
        }
        return array('search'=>$search,'where'=>$where);
    }

    /**
     * 列表
     * @param array $condition
     * @param int $page_size
     * @param string $order_by
     * @return \think\Paginator
     */
    public function _list_two($condition = [], $page_size = PAGE_SIZE_ADMIN, $order_by = 'sort asc'){
        $obj = $this->alias('u')
            ->field('u.*, cc.cate_title,dd.chapter_title')
            ->join('sy_tk_chapters dd', 'dd.id = u.chapter_cate', 'LEFT')
            ->join('sy_tk_cates cc', 'cc.id = u.cate', 'LEFT')
            ->where('u.chapter_type',1)
            ->order('id desc');
        $result = get_page($obj, $condition, $page_size);
        $result0 = $result['list']->all();
        foreach ($result0 as $k=>$v){
            $map0['detail_id'] = $v['id'];
            $map0['q_type']    = 1;
            $q_number_one = Single::where($map0)->count();
            $map1['detail_id'] = $v['id'];
            $map1['q_type']    = 2;
            $q_number_two = Single::where($map1)->count();
            $map2['detail_id'] = $v['id'];
            $map2['q_type']    = 3;
            $q_number_three = Single::where($map2)->count();
            $v['q_number_one']      = $q_number_one;
            $v['q_number_two']      = $q_number_two;
            $v['q_number_three']    = $q_number_three;
            $result['list'][$k] = $v;
        }
        return $result;
    }

    /**
     * 获取条件
     */
    public function _where_two($request){
        $p = isset($request['page']) ? $request['page'] : 1;
        $start = isset($request['start']) ? $request['start'] : '';
        $end = isset($request['end']) ? $request['end'] : '';
        $title = isset($request['detail_title']) ? $request['detail_title'] : '';

        $request['page'] = $p;
        $request['start'] = $start;
        $request['end'] = $end;
        $request['detail_title'] = $title;
        $search = $request;

        $title = htmlspecialchars(addslashes(str_replace(' ', '', $request['detail_title'])));
        $request['detail_title'] = str_replace('%', "\%", $title);

        $request['start'] = empty($request['start']) ? '' : strtotime($request['start']);
        $request['end'] = empty($request['end']) ? '' : strtotime($request['end']);
        $tmp = $request;
        foreach($tmp as $k=>$v){
            if(empty($v)){
                unset($tmp[$k]);
            }
        }
        $where = '';
        foreach($tmp as $k=>$v){
            if($k == 'start'){
                $start = strtotime($v);
                $where .= "u.created >= $start and ";
            }elseif($k == 'end'){
                $end = strtotime($v) + 24*3600;
                $where .= "u.created <= $end and ";
            }elseif($k == 'detail_title'){
                $where .= "u.detail_title like '%$v%' and ";
            }
        }
        if(!empty($where)){
            $where = substr($where, 0, -4);
        }
        return array('search'=>$search,'where'=>$where);
    }


    /**
     * 获取题库章节列表
     */
    public function _get_exam_list($cate,$chapter_type,$uid){

        $maps['cate']         = $cate;
        $maps['chapter_type'] = $chapter_type;
        $data = $this->where($maps)->field('id,detail_title')->all()->toArray();
        foreach ($data as $k=>$v){
            $back_info = $this->_get_all_and_done($v['id'],$uid);
            $data[$k]['total_number'] = $back_info['total'];
            $data[$k]['right_number'] = $back_info['right'];
            $data[$k]['score']        = $back_info['score'];
        }
        return $data;
    }

    /**
     * 获取已完成和总题数
     */
    public function _get_all_and_done($detail_id,$uid){
        $total = Db::name('tk_single')->where('detail_id',$detail_id)->count();
        $maps0['detail_id'] = $detail_id;
        $maps0['uid']       = $uid;
        $right_number = Db::name('tk_record')->where($maps0)->value('right_number');
        $total_score  = Db::name('tk_record')->where($maps0)->value('total_score');
        if(!$total){
            $total = 0;
        }
        if(!$right_number){
            $right_number = 0;
        }
        if(!$total_score){
            $total_score = 0;
        }
        $back['total'] = $total;
        $back['right'] = $right_number;
        $back['score'] = $total_score;
        return $back;
    }

    /**
     * 获取题库章节列表
     */
    public function _get_test_question($detail_id,$uid){

        $data  = $this->field('id,detail_title,chapter_year,chapter_score,chapter_time,chapter_number,chapter_introduce,chapter_type')
            ->get($detail_id)
            ->toArray();
        $question_info = Single::where('detail_id',$detail_id)
            ->order('q_num asc')
            ->all()
            ->toArray();
        $maps0['uid']   = $uid;
        $collection_arr = Db::name('tk_collection')->where($maps0)->column('single_id');
        foreach ($question_info as $k=>$v){
            if(in_array($v['id'],$collection_arr)){
                $question_info[$k]['is_collection'] = 1;
            }else{
                $question_info[$k]['is_collection'] = 0;
            }
        }
        $data['question_info'] = $question_info;
        return $data;
    }

}